package main

import (
	"encoding/binary"
	"fmt"
	"math"
	"strconv"
)

func main() {
	var f32 = 23.3
	fmt.Println("32位浮点数：", f32)
	var str string
	//str = strconv.Itoa(f32)
	fmt.Println("转换成字符串", str)
	//将一个字符串转换成浮点数
	var strfloat string = "23.43"
	newf64, _ := strconv.ParseFloat(strfloat, 32)
	fmt.Println("新转换后的数值:", newf64)

	//将float转换为字节
	bys := Float32ToByte(23.2)                     //转换成字节切片
	fmt.Println("将字节切片转化成浮点：", ByteToFloat32(bys)) //将字节切片转换成

	//将浮点类型的值转换成为字符串
}

//将float32转换成byte切片
func Float32ToByte(float float32) []byte {
	bits := math.Float32bits(float)
	bytes := make([]byte, 4) //四个字节 32位
	binary.LittleEndian.PutUint32(bytes, bits)
	return bytes
}

//将byte切片转换成float32
func ByteToFloat32(bytes []byte) float32 {
	bits := binary.LittleEndian.Uint32(bytes)
	return math.Float32frombits(bits)
}

//将float64转换成byte切片
func Float64ToByte(float float64) []byte {
	bits := math.Float64bits(float)
	bytes := make([]byte, 8) //八个字节 64位
	binary.LittleEndian.PutUint64(bytes, bits)
	return bytes
}

//将byte切片转换成float64
func ByteToFloat64(bytes []byte) float64 {
	bits := binary.LittleEndian.Uint64(bytes)
	return math.Float64frombits(bits)
}
